package py.com.alfa.escriba.gui.spring.processors;

import java.lang.reflect.Field;

import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.ReflectionUtils.FieldCallback;
import org.winter.utils.ClassUtils;

import py.com.alfa.escriba.gui.utils.LoggerUtils;



public class LogUtilsPostProcessor implements BeanPostProcessor {
 
    public Object postProcessAfterInitialization(Object bean, String beanName) throws
        BeansException {
        return bean;
    }
 
    public Object postProcessBeforeInitialization(final Object bean, String beanName)
          throws BeansException {
       
    	ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
			
			public void doWith(Field field) throws IllegalArgumentException,
					IllegalAccessException {
				ReflectionUtils.makeAccessible(field);

				// Check if the field is annoted with @LogUtils
				if (field.getAnnotation(LogUtils.class) != null) {
					LogUtils logUtilsAnnotation = field.getAnnotation(LogUtils.class);
					Class<?> clazz = logUtilsAnnotation.value();
					LoggerUtils instance  = (LoggerUtils) ClassUtils.getClassInstance(field.getType());
					instance.setLogger(LoggerFactory.getLogger(clazz));
					field.set(bean, instance);
				}
			}
		});
 
        return bean;
    }
}
